package com.ftqh.tutorial.security.core.userdetails;

import com.ftqh.tutorial.security.entity.Role;
import com.ftqh.tutorial.security.entity.User;
import com.ftqh.tutorial.security.repository.RoleRepository;
import com.ftqh.tutorial.security.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;
import java.util.Set;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: Administrator
 * \* Date: 2016/12/27
 * \* Time: 18:21
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleRepository roleRepository;

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<User> user= userRepository.findByUsername(username);
        return user.map(u-> {
            Set<Role> roles = roleRepository.findGroupRolesByUserId(u.getId());
            u.addRoles(roles);
            return u;
        }).orElseThrow(() -> new UsernameNotFoundException("Could not find user: " + username));
    }
}
